package com.nkzy.controller;

import com.nkzy.domain.User;
import com.nkzy.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.IntStream;

/**
 * Create by 王建烨 on 2022/4/15 10:30
 **/

@Controller
public class PageController {

    @Resource
    private UserService userService;

    @GetMapping("/addUser")
    public String addUser(Model model){
        return "addUser";
    }

    @GetMapping("/editUser/{id}")
    public String editUser(Model model,@PathVariable Integer id){
        try {
            User user = userService.query(id);
            model.addAttribute("user",user);
        }catch (Exception e){
            e.printStackTrace();
            model.addAttribute("msg","原因："+e.getMessage());
            model.addAttribute("redirect","/editUser/"+id);
            return "error";
        }
        return "editUser";
    }

    @GetMapping("/userList")
    public String showUserList(Model model,Integer page){
        try{
            if(page == null || page<=1){
                page = 1;
            }
            Integer totalPage = userService.queryTotalPagination(5);
            System.out.println(totalPage);
            List<User> userList = userService.queryUserByPagination(5,page);
            model.addAttribute("nowPage", page);
            model.addAttribute("totalPage",totalPage);
            model.addAttribute("userList",userList);
        }catch (Exception e){
            e.printStackTrace();
            model.addAttribute("msg","原因："+e.getMessage());
            model.addAttribute("redirect","userList");
            return "error";
        }
        return "userList";
    }

}
